const router = require("koa-router")();
const Mock = require("mockjs");
const JWT = require("jsonwebtoken");
let user = [
  {
    username: "admin",
    password: "admin",
    info: "https://robohash.org/6666666?set=set4",
    row: "admin",
  },
  {
    username: "user",
    password: "user",
    info: "https://robohash.org/5555?set=set2",
    row: "user",
  },
];
let { list, tab, city } = Mock.mock({
  "list|10": [
    {
      img: "@image(100x100,@color)",
      title: "@ctitle(2)",
      "price|10-100": 1,
      word: "@cword(4)",
      id: "@id",
    },
  ],
  "tab|5": [
    {
      title: "@ctitle(2)",
      "children|10": [
        {
          img: "@image(100x100,@color)",
          "price|10-100": 1,
          title: "@cword(2)",
          word: "@cword(5)",
          id: "@id",
        },
      ],
    },
  ],
  "city|30": [
    {
      city: "@city",
    },
  ],
});

router.get("/search", (ctx, next) => {
  let { val } = ctx.request.query;
  let items = list.filter((item) => item.title.includes(val));
  if (items) {
    ctx.body = {
      code: 200,
      items,
    };
  } else {
    ctx.body = {
      code: 200,
      list,
    };
  }
});

router.get("/city", (ctx, next) => {
  ctx.body = {
    code: 200,
    city,
  };
});

router.get("/tab", (ctx, next) => {
  ctx.body = {
    code: 200,
    tab,
  };
});

router.get("/list", (ctx, next) => {
  ctx.body = {
    code: 200,
    list,
  };
});

router.post("/sigin", (ctx) => {
  let { username, password } = ctx.request.body;
  let items = user.find(
    (item) => item.username == username && item.password == password
  );

  if (items) {
    ctx.body = {
      code: 400,
      msg: "账号密码已存在，注册失败",
    };
  } else {
    user.push({
      ...ctx.request.body,
      info: "https://robohash.org/333?set=set5",
      row: "admin",
    });
    ctx.body = {
      code: 200,
      msg: "注册成功",
    };
  }
});

router.post("/login", (ctx) => {
  let { username, password } = ctx.request.body;
  let items = user.find(
    (item) => item.username == username && item.password == password
  );
  console.log(items)
  if (items) {
    ctx.body = {
      code: 200,
      msg: "登录成功",
      token: JWT.sign(items.username, "sdff334ff"),
      user: items.username,
      info: items.info,
      row: items.row,
    };
  } else {
    ctx.body = {
      code: 400,
      msg: "登录失败,请重新登录",
    };
  }
});

router.get("/detail", (ctx) => {
  let { id } = ctx.request.query;
  let items = list.find((item) => item.id == id);
  if (items) {
    ctx.body = {
      code: 200,
      msg: "数据获取成功",
      items,
    };
  } else {
    ctx.body = {
      code: 400,
      msg: "数据获取失败",
    };
  }
});

router.delete("/del", (ctx) => {
  let { id } = ctx.request.query;
  list = list.filter((item) => item.id !== id);
  ctx.body = {
    code: 200,
    msg: "删除成功",
  };
});

module.exports = router;
